package dbinit

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"iot-base/common/dbconn"
	"os"
	"path/filepath"

	"iot-base/common/dbobj"
	"iot-base/common/logger"
)

func loadDB(path string, ftype string, force bool) {
	files, _ := ioutil.ReadDir(path)
	fmt.Println("***********read defaultdb*********", len(files))

	for _, mfile := range files {
		var dbobji interface{}
		switch ftype {
		case "tmodel":
			dbobji = &dbobj.TModel{}
		case "catalog":
			var catalogs []dbobj.Catalog
			dbobji = &catalogs
		}
		if dbobji != nil {
			filename := path + "/" + mfile.Name()
			logger.SLog.Info("begin init db from ", filename)
			data, err := ioutil.ReadFile(filename)
			if err == nil {
				err = json.Unmarshal(data, dbobji)
				if err == nil {
					if ftype == "tmodel" {
						err := dbconn.DBConnection.Create(dbobji).Error
						if err != nil && force {
							logger.SLog.Info("retry---------save to db", filename)
							err = dbconn.DBConnection.Save(dbobji).Error

						}
						if err != nil {
							logger.SLog.Error("db error init", "error", err, filename, force)
						}
					} else {
						dbconn.DBConnection.Save(dbobji)
					}

				}
			} else {
				logger.SLog.Error("db error", "error", err)
			}
		}
	}

}
func initByDir() {
	fmt.Println("**************************************###########################")
	fmt.Println("***********ooo************************###########################")
	fmt.Println("**********ooo*************************###########################")
	fmt.Println("********ooo***************************###########################")
	fmt.Println("*******ooo****************************###########################")
	fmt.Println("**************************************###########################")

	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	path := dir + "/defaultdb"
	fmt.Println("0---------*********************--------", dir)

	loadDB(path+"/catalog", "catalog", false)
	loadDB(path+"/tmodel", "tmodel", false)
	loadDB(path+"/fcatalog", "catalog", true)
	loadDB(path+"/ftmodel", "tmodel", true)

}

func init() {
	fmt.Println("***********init db*********")
	dbconn.DBConnection.AutoMigrate(&dbobj.Area{})
	dbconn.DBConnection.AutoMigrate(&dbobj.TModel{})
	dbconn.DBConnection.AutoMigrate(&dbobj.Catalog{})
	//dbconn.DBConnection.AutoMigrate(&Business{})
	dbconn.DBConnection.AutoMigrate(&dbobj.Station{})
	dbconn.DBConnection.AutoMigrate(&dbobj.Thing{})
	//dbconn.DBConnection.AutoMigrate(&dbobj.ThingConnection{})
	dbconn.DBConnection.AutoMigrate(&dbobj.ThingStation{})
	//dbconn.DBConnection.AutoMigrate(&StationBusiness{})
	//dbconn.DBConnection.AutoMigrate(&Rule{})
	//dbconn.DBConnection.AutoMigrate(&StationRule{})

	dbconn.DBConnection.AutoMigrate(&dbobj.ThingParam{})
	dbconn.DBConnection.Exec("Drop INDEX mp_index")
	dbconn.DBConnection.AutoMigrate(&dbobj.TModelProtocol{})
	dbconn.DBConnection.AutoMigrate(&dbobj.CommonProperty{})
	dbconn.DBConnection.AutoMigrate(&dbobj.VideoRelation{})
	dbconn.DBConnection.AutoMigrate(&dbobj.ThingState{})
	dbconn.DBConnection.AutoMigrate(&dbobj.ThingMaintainInfo{})
	dbconn.DBConnection.AutoMigrate(&dbobj.ThingAlarmRule{})
	dbconn.DBConnection.AutoMigrate(&dbobj.AlarmShield{})

	dbconn.DBConnection.Exec("ALTER TABLE stations ALTER COLUMN area_id type varchar(100) using area_id::varchar(100);")
	dbconn.DBConnection.Exec("ALTER TABLE areas ALTER COLUMN uid type varchar(100) using uid::varchar(100);")

	initByDir()
	var count int64
	dbconn.DBConnection.Model(&dbobj.Catalog{}).Count(&count)
	if count == 0 {
		var commonCatalog dbobj.Catalog
		commonCatalog.UID = "COMMON"
		commonCatalog.SName = "common"
		dbconn.DBConnection.Save(commonCatalog)
	}

}
